package liuyao.webutils.filter;

import liuyao.webutils.config.ProjectConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class UrlFiler implements Filter {

    @Autowired
    ProjectConfig config;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String uri = request.getRequestURI()
                .replaceFirst(request.getContextPath(), "");
        if (config.getBlackUriFull().contains(uri)) {
            response.setStatus(403);
            return;
        }
        for (String pre : config.getBlackUriPrefix()) {
            if (uri.startsWith(pre)) {
                response.setStatus(403);
                return;
            }
        }
        //继续请求
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
